const app = getApp();
import {ordedownload, orderInfo, getOrderReturnAddress, orderReturnAddExpress, orderApplyReturn, getReturnExpressList, orderReturnCancel, orderPreAuth, getRenewalGoodsStatus, orderBuyDeposit } from "../../../api/order";
import { getBtnsByStatus, cancelOrder, cancelRefundApply, confirmReceipt, payFirstRent } from "../../../utils/order";
import { disposeData } from "../../../utils/outData";
import { baseImgUrl } from "../../../setting";
Page({
  data: {
    orderTip: '',
    order_id: '',
    goodsData: {},
    btns: [],
    showMore: true,
    showService: false,
    returnAddress: {},
    addressModal: false,
    addressBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '复制地址', extClass: 'button2' },
    ],
    addressOneBtn: [
      { text: '返回', extClass: 'button1' },
    ],
    returnModal: false,
    returnBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '确认归还', extClass: 'button2' },
    ],
    returnApplyBtn: [
      { text: '取消申请', extClass: 'button1' },
      { text: '确认申请', extClass: 'button2' },
    ],
    order_id: '',
    status: 0,
    flowModal: false,
    flowList: [],
    flowIndex: -1,
    flowNo: '',
    placeholder: '请填写物流单号',
    disabledInput: false
  },
  closeService() {
    this.setData({
      showService: false
    })
  },
  onLoad(options) {
    this.setData({
      order_id: options.id || disposeData().id
    })
    this.getData();
  },
  goToBill(e) {
    const order_id = e.currentTarget.dataset.id;
    my.navigateTo({
      url: '../../bill/bill?order_id=' + order_id + '&isView=' + true
    });
  },
  toSnapshot(e) {
    const { goodsId, orderId } = e.currentTarget.dataset
    my.navigateTo({
      url: '../../orderSnapshot/orderSnapshot?goodsId=' + goodsId + '&orderId=' + orderId
    })
  },
  onReletClick(){
    const {goodsId, setmealId, goodsStatus, order_id } = this.data
    if(!goodsStatus){
      this.setData({
        reletModal: false,
        goodsStatus: ''
      })
    } else {
      my.navigateTo({
        url: "../../productDetails/productDetails?goodsId=" +goodsId+ '&setmealId=' +setmealId+ '&is_renewal=' +1+ '&parent_order_id=' + order_id
      })
    }
  },
  checkProtocol() {
      const orderid=this.data.order_id
    if (!this.data.goodsData || !this.data.goodsData.pact_url) {
      my.showToast({
        type: 'none',
        content: '还未签署协议',
        duration: 2000
      });
      return;
    }
    my.showLoading({ content: '正在下载协议...' });
    // my.downloadFile({
    //   url: baseImgUrl + this.data.goodsData.pact_url,
    //   success({ apFilePath }) {
    //     my.hideLoading();
    //     my.openDocument({
    //       filePath: apFilePath,
    //       fileType: 'pdf',
    //       success: (res) => {
    //         console.log('open document success')
    //       }
    //     })
    //   }
    // })

    ordedownload(orderid).then((res)=>{
    my.downloadFile({
      url: res,
      success({ apFilePath }) {
        my.hideLoading();
        my.openDocument({
          filePath: apFilePath,
          fileType: 'pdf',
          success: (res) => {
            console.log('open document success')
          }
        })
      }
    })
    })
 
  },
  checkOldOrder(){
    if(getCurrentPages().length === 5){
      my.redirectTo({
        url: './orderpay?id=' + this.data.goodsData.parent_order_id
      });
    } else {
      my.navigateTo({
        url: './orderpay?id=' + this.data.goodsData.parent_order_id
      })
    }
  },
  checkReletOrder(){
    if(getCurrentPages().length === 5){
      my.redirectTo({
        url: './orderpay?id=' + this.data.goodsData.sub_order_id
      });
    } else {
      my.navigateTo({
        url: './orderpay?id=' + this.data.goodsData.sub_order_id
      })
    }
  },
  getOrderTip(status) {
    switch (status) {
      case 2:
        this.setData({ orderTip: '预计两个小时后自动关闭订单，请及时处理' });
        break;
      case 10:
        this.setData({ orderTip: '审核发货预计需要3个工作日，请保持手机畅通' });
        break;
      case 11:
        this.setData({ orderTip: '审核退款预计1—3个工作日，请保持手机畅通' });
        break;
      case 20:
        this.setData({ orderTip: '您的订单已发货，请及时收货' });
        break;
      case 1:
        this.setData({ orderTip: '您的订单已取消' });
        break;
      case 60:
        this.setData({ orderTip: '您的订单已完成' });
        break;
      case 30:
        const { lease_time, month_total } = this.data.goodsData;
        const tip = '您的订单租期：' + lease_time + '（共' + month_total + '月）到期后请及时处理（归还、续租、买断）';
        this.setData({ orderTip: tip });
        break;
      case 13:
        this.setData({ orderTip: '商家拒绝退款，拒绝原因：' });
        break;
      case 16:
        const { setmeal_foregift, pay_type } = this.data.goodsData;
        this.setData({ orderTip: '您的订单已退款' + (pay_type == 2 ? '，已退回冻结押金￥' + setmeal_foregift : '') })
        break;
      case 41:
        this.setData({ orderTip: '您已申请归还，请主动联系商家进行处理，商家会在3个工作日内确认是否同意归还。' })
        break;
      case 42:
        this.setData({ orderTip: '商家已同意归还，请填写归还物流信息' })
        break;
      case 44:
        this.setData({ orderTip: '您已发货，等待商家收货' })
        break;
      case 45:
        this.setData({ orderTip: '商家已确认收货' })
        break;
      case 43:
        this.setData({ orderTip: '商家未同意归还，请联系商家' })
        break;
      case 62:
        const { buyout_amount } = this.data.goodsData;
        this.setData({ orderTip: '实付买断金额：￥' + buyout_amount });
        break;

      default:
        break;
    }
  },
  getData() {
    orderInfo(this.data.order_id).then(res => {
      my.stopPullDownRefresh();
      const btns = getBtnsByStatus(res).filter(item => item.id != 9);
      this.setData({
        goodsData: res || {},
        btns
      })
      this.getOrderTip(this.data.goodsData.status);
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  goToShop() {

    // my.navigateTo({
    //   url: '../../storeDetails/storeDetails?member_id=' + this.data.goodsData.member_id
    // });
    my.navigateTo({
      url: '../../storeDetails/storeDetails?member_id=' + this.data.goodsData.member_id +"&shopname=" +this.data.goodsData.shopname
    });
  },
  copyOrderNum() {
    my.setClipboard({
      text: this.data.goodsData.trade_no,
      success: () => {
        my.alert({
          content: '已复制',
          buttonText: '我知道了'
        })
      }
    });
  },
  clickMore() {
    this.setData({
      showMore: !this.data.showMore
    })
  },
  btnClick(e) {
    this.setData({
      showMore: false
    });
    const that = this;
    const { id, status, order_id, isAuth, pay_type, esignUserId, flowId, sign_status, goods_id, contract_type } = e.currentTarget.dataset;
    this.setData({
      order_id,
      status
    })
    if (id == 2) {
      cancelOrder(order_id, function () {
        that.getData();
      })
    }
    if (id == 9) {
      my.navigateTo({
        url: '../../applyRefund/applyRefund?order_id=' + order_id
      });
    }
    if (id == 18) {
      cancelRefundApply(order_id, function () {
        that.getData();
      })
    }
    if (id == 3 && status == 20) {
      confirmReceipt(order_id, function () {
        that.getData();
      })
    }
    if ((id == 6 && status == 44) || id == 19) {
      my.navigateTo({
        url: '../../logistics/logistics?order_id=' + order_id
      });
    }
    if (id == 4) {
      my.navigateTo({
        url: '../../bill/bill?order_id=' + order_id
      });
    }
    console.log(id,status,sign_status)
    // debugger
    if ((id == 1 || id == 20) && (status == 2 || sign_status != 2)) {
      my.navigateTo({
        url: '../../authentication/authentication?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&status=' + status + '&contractType=' + contract_type
      });
    }
    if ((id == 1 || id == 20) && (status == 3 && sign_status == 2)) {
      my.navigateTo({
        url: '../../bill/bill?order_id=' + order_id
      })
    }
    if (id == 17) {
      this.setData({
        showService: true
      })
    }
    if (id == 7) {
      my.navigateTo({
        url: '../../productDetails/productDetails?goodsId=' + goods_id
      });
    }
    if (id == 14) {
      my.navigateTo({
        url: '../../buyout/buyout?orderId=' + order_id
      });
    }
    // 立即归还
    if (id == 11) {
      if(status == 40){
        this.setData({
          returnModal: true
        })
      } else if(status == 42){
        getReturnExpressList().then(res =>{
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      }
    }
    // 获取归还地址
    if (id == 16) {
      getOrderReturnAddress(order_id).then(res => {
        if(res){
          this.setData({
            returnAddress: res,
            addressModal: true
          })
        }
      }).catch(err => {
        this.setData({
          addressModal: false
        })
      })
    }
    // 取消归还
    if(id == 5){
      orderReturnCancel(order_id).then(res =>{
        my.showToast({
          type: 'none',
          content: '操作成功',
          duration: 1000,
        });
        that.getData();
      })
    }
    // 申请归还
    if(id == 10){
      this.setData({
        returnModal: true
      })
    }
    // 再次申请
    if(id == 12){
      orderApplyReturn(order_id).then(res =>{
        that.getData();
      })
    }
    // 重新签约
    if(id == 22){
      that.againPreAuth();
    }
    // 申请续租
    if(id == 15){
      getRenewalGoodsStatus(order_id).then(res =>{
        const {goods_id, setmeal_id, status } = res
        if(status == 1){
          this.setData({
            reletModal: true,
            goodsStatus: status,
            goodsId: goods_id,
            setmealId: setmeal_id
          })
        } else {
          this.setData({
            reletModal: true,
            goodsStatus: '',
          })
        }
      }).catch(err =>{
        this.setData({
          reletModal: false,
          goodsStatus: '',
        })
      })
    }
  },
  // 签约预授权
  againPreAuth(){
    const that = this
    orderPreAuth(that.data.order_id).then(res =>{
        if(res.orderStr){
          my.tradePay({
            orderStr: res.orderStr,
            success: (res) => {
              that.getData();
            },
            fail: (res) => {
              my.showToast({
                type: 'fail',
                content: '签约失败，请稍后重试',
                duration: 1000,
              });
            }
          });
        }
    })
  },
  onAddressClick(e) {
    let index = e.target.dataset.index
    if (index == 0) {
      this.setData({
        addressModal: false,
      });
    } else {
      my.setClipboard({
        text: this.data.returnAddress,
        success: () => {
          my.showToast({
            type: 'none',
            content: '复制成功',
            duration: 1000,
          });
        }
      });
    }
  },
  onReturnClick(e) {
    const that = this
    let index = e.target.dataset.index
    if (index == 0) {
      that.setData({
        returnModal: false,
      });
    } else {
      const {order_id, status} = that.data
      if(status == 40){
        getReturnExpressList().then(res =>{
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      } else if( status==30|| status==39 ){
        orderApplyReturn(order_id).then(res =>{
          that.getData();
          that.setData({
            returnModal: false
          });
        })
      }
    }
  },
  bindPickerChange(e){
    this.setData({
      flowIndex: e.detail.value,
      disabledInput: e.detail.value == 0 ? true : false,
      placeholder: e.detail.value == 0 ? '无需填写单号' : '请填写物流单号',
    });
  },
  onFlowNo(e){
    let reg = /^[0-9A-Za-z]+$/
    console.log(reg.test(e.detail.value))
    if(!reg.test(e.detail.value)){
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
    }
    this.setData({ flowNo: e.detail.value })
  },
  toAddFlow(){
    const that = this
    const { order_id, flowIndex, flowNo, flowList} = that.data
    const reg = /^[0-9A-Za-z]+$/
    if(flowIndex < 0){
      my.showToast({
        type: 'none',
        content: '请选择物流名称',
        duration: 1500,
      });
      return false 
    }
    if(!flowNo && flowIndex >0){
      my.showToast({
        type: 'none',
        content: '请填写物流单号',
        duration: 1500,
      });
      return false 
    }
    if(flowNo && !reg.test(flowNo)){
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
      return false
    }
    orderReturnAddExpress({
      order_id,
      logistics_name: flowList[flowIndex].name,
      logistics_no: flowNo,
    }).then(res =>{
      this.setData({
        flowModal: false
      });
      that.getData();
    })
  },
  closeModal(){
    this.setData({
      flowModal: false
    })
  },
  onPullDownRefresh() {
    this.getData();
  },
  deposit() {
    const { order_id } = this.data;
    orderBuyDeposit(order_id).then(res => {
      if (res.trade_no) {
        my.tradePay({
          tradeNO: res.trade_no,
          success: (res) => {
            console.log(JSON.stringify(res));
            if (res.resultCode == 9000) {
              my.navigateTo({
                url: '../buyoutSuccess/buyoutSuccess?orderId=' + orderId
              });
            } else {
              my.showToast({
                type: 'fail',
                content: '支付失败，请稍后重试',
                // content: JSON.stringify(res),
                duration: 1000,
              });
            }
          }
        });
      }
    })
  },

  cancelOrder() {
    const { order_id } = this.data;
    cancelOrder(order_id, function () {
      that.getData();
    })
  }
});
